package com.itheima.controller;

import cn.hutool.core.lang.Snowflake;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import com.itheima.vo.CategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author CSY
 * 2022/5/9    19:03
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<CategoryVo> page(int page,int pageSize){

        List<Category> categoryVos = categoryService.selectPage(page, pageSize);
        CategoryVo categoryVo = new CategoryVo();
        
        categoryVo.setRecords(categoryVos);
        categoryVo.setSize(pageSize);
        categoryVo.setTotal(categoryService.selectCount());
        categoryVo.setCurrent(page);

        return R.success(categoryVo);
    }

    /**
     * 根据id删除分类
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam Long id){
        int i = categoryService.deleteById(id);
        return i>0?R.success("删除成功"):R.error("删除失败");
    }

    /**
     * 添加的方法
     * @param category
     * @return
     */
    @PostMapping
    public R<String> insert(@RequestBody Category category){

        String id = new Snowflake().nextIdStr();
        String createUser = TokenHolder.getCurrentId();
        category.setId(Long.valueOf(id));

        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(Long.valueOf(createUser));
        category.setUpdateUser(Long.valueOf(createUser));


        categoryService.insert(category);

        return R.success("添加成功");

    }
    @PutMapping
    public R<String> update( @RequestBody Category category){

        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(Long.valueOf(TokenHolder.getCurrentId()));
        int i = categoryService.updateById(category);

        return i>0? R.success("修改成功"):R.error("修改失败");

    }
    @GetMapping("/list")
    public R<List<Category>> list(@RequestParam int type){

        List<Category> categories = categoryService.selectByType(type);

        return R.success(categories);
    }



}
